package com.xrun.risk.service.process.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xrun.cmap.WfMapUtils;
import com.xrun.common.constant.ThirdTypeConstants;
import com.xrun.common.utils.DateUtils;
import com.xrun.ocenengine.dto.vo.AgentTokenAndTypeVo;
import com.xrun.risk.domain.WfRiskDeleteTask;
import com.xrun.risk.domain.WfRiskDeleteTaskAdter;
import com.xrun.risk.domain.WfRiskDeleteTaskAdterContentDetail;
import com.xrun.risk.dto.req.ThirdLoadingGetReq;
import com.xrun.risk.mapper.WfRiskDeleteTaskAdterContentDetailMapper;
import com.xrun.risk.service.process.Process;
import com.xrun.risk.util.ThirdLocalLandingPageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ThirdSiteProcessImpl implements Process {
    @Autowired
    private  ThirdLocalLandingPageUtil thirdLocalLandingPageUtil;
    @Autowired
    private WfRiskDeleteTaskAdterContentDetailMapper wfRiskDeleteTaskAdterContentDetailMapper ;

    @Override
    public Object execute(WfRiskDeleteTask wfRiskDeleteTask,
                        WfRiskDeleteTaskAdter record,
                          AgentTokenAndTypeVo vo) {


        if(ThirdTypeConstants.AD.equals(vo.getThirdType())){
          return  this.dealForAD(wfRiskDeleteTask, record, vo);
        }else {
            //qc没有橙子落地页，ad才有
          return null;
        }


    }

    /**
     * 千川处理逻辑
     * @param wfRiskDeleteTask
     * @param record
     * @param vo
     * @return
     */
    private Object dealForQC(WfRiskDeleteTask wfRiskDeleteTask,
                             WfRiskDeleteTaskAdter record,
                             AgentTokenAndTypeVo vo) {





        return null ;
    }

    /**
     * ad 处理逻辑
     * @param wfRiskDeleteTask
     * @param record
     * @param vo
     * @return
     */
    private Object dealForAD(WfRiskDeleteTask wfRiskDeleteTask,
                        WfRiskDeleteTaskAdter record,
                          AgentTokenAndTypeVo vo) {

        //获取所有第三方站点列表
        List<String> ids =this.getAllSite(record.getAdvertiserId(), WfMapUtils.get(vo.getTokenTableId()));

        if (CollectionUtil.isEmpty(ids)){
            return null ;
        }

        //构造对象
        Map<String, WfRiskDeleteTaskAdterContentDetail> contentDetails = WfRiskDeleteTaskAdterContentDetail.getListEntityContent(
                ids, record, vo, wfRiskDeleteTask, "ThirdSite");

        //进行删除
        List<WfRiskDeleteTaskAdterContentDetail> results = this.deleteSite(vo.getTokenTableId(), record.getAdvertiserId()+"",
                ids,contentDetails,vo.getThirdType());

        //本地存储
        wfRiskDeleteTaskAdterContentDetailMapper.batchInsert(results);
           return null ;
    }



    /**
     * 获取所有站点id
     * @param advertiserId
     * @param accessToken
     * @return
     */
    private List<String> getAllSite(Long advertiserId, String accessToken) {
        List<String> objects = new ArrayList<>();

        ThirdLoadingGetReq req = new ThirdLoadingGetReq();
        req.setAdvertiserId(advertiserId);
        int currentPage = 1;
        int totalNum = 0;
        do {
            req.setPage(currentPage);
            req.setPageSize(100);
           //获取2年前日期
            String  startTime =DateUtil.format( DateUtil.offsetMonth(new Date(), -720), "yyyy-MM-dd");;
            req.setStartTime(startTime);
            req.setEndTime(DateUtils.getDate());
            req.getStartTime();
            req.getEndTime();
            JSONObject jsonObject = thirdLocalLandingPageUtil.thirdSiteGet(accessToken, req);
            totalNum = jsonObject.getJSONObject("data").getJSONObject("page_info").getInteger("total_page");
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray jsonArray = data.getJSONArray("list");
            if (CollectionUtil.isNotEmpty(jsonArray)){
                for (int i = 0; i < jsonArray.size(); i++) {
                    objects.add(jsonArray.getJSONObject(i).getString("site_id"));
                }
            }
        currentPage++;
        }while (currentPage <= totalNum);
        return objects ;
    }

    /** 删除站点素材
     *
     * @param tokenTableId
     * @param accountId
     * @param ids
     * @param contentDetails
     * @param thirdType
     * @return
     */
    private List<WfRiskDeleteTaskAdterContentDetail> deleteSite(String tokenTableId, String accountId, List<String> ids,
                                                                Map<String, WfRiskDeleteTaskAdterContentDetail> contentDetailsMap, String thirdType) {

        for (String siteIds : ids) {
            try {
                JSONObject jsonObject =  thirdLocalLandingPageUtil.deleteThirdSite(Long.parseLong(accountId),
                        WfMapUtils.get(tokenTableId), Long.parseLong(siteIds));
                Long successDeleceSite = jsonObject.getJSONObject("data").getLong("site_id");
                WfRiskDeleteTaskAdterContentDetail one = contentDetailsMap.get(siteIds);
                if (successDeleceSite==null){
                      one.setClearStatus("2");//2清理失败
                      one.setFailReason(jsonObject.getString("message"));
                      contentDetailsMap.put(siteIds,one);
                }else{
                    one.setClearStatus("1");//1清理成功
                    contentDetailsMap.put(siteIds,one);
                }
            } catch (Exception e) {
                  WfRiskDeleteTaskAdterContentDetail one = contentDetailsMap.get(siteIds);
                      one.setClearStatus("2");//2清理失败
                      one.setFailReason(JSONObject.parseObject(e.getMessage()).getJSONObject("result").getString("message"));
                      contentDetailsMap.put(siteIds,one);
            }
        }
        return new ArrayList<>(contentDetailsMap.values());
    }
}